﻿#include"head.h"

//便捷输入
void GetInt(int *a) {
	scanf_s("%d", a);
}

//哈希函数
int HashFunction(int key, int size) {
	return key % size;
}

//初始化哈希表
void init_hash(int size, HashTable* ht) {
	ht->table = (HashData*)malloc(sizeof(HashData) * size);
	ht->size = size;
	for (int i = 0; i < size; i++) {
		ht->table[i].key = 0;
		ht->table[i].value = 0;
	}
}

//插入操作
void Insert(HashTable* ht, int key, int value) {
	int originalindex = HashFunction(key,ht->size);
	int index = originalindex;
	//冲突处理
	while (ht->table[index].key != 0) {
		index = (index + 1) % ht->size;
		//判满
		if (index == originalindex) {
			printf("HashTable已满！\n");
			return;
		}
	}
	//插入数据
	ht->table[index].key = key;
	ht->table[index].value = value;
}

//查找操作A（据关键字找数据）
int ScarchByKey(HashTable* ht, int key) {
	int originalindex = HashFunction(key, ht->size);
	int index = originalindex;
	//逆冲突处理
	while (ht->table[index].key != 0) {
		if (ht->table[index].key == key) { return ht->table[index].value; }
		index = (index + 1) % ht->size;
		//没有对应的key
		if (index == originalindex) { break; }
	}
	return -1;
}

//查找操作B（据位置找数据）
int ScarchByLocation(HashTable* ht, int location) { return ht->table[location-1].value; }

//插查合并操作
int SAI(HashTable* ht, int key, int value) {
	int originalindex = HashFunction(key, ht->size);
	int index = originalindex;
	//逆冲突查找
	while (ht->table[index].key != 0 ) {
		if (ht->table[index].key == key) { return 1; }
		index = (index + 1) % ht->size;
		//表满
		if (index == originalindex) { return -1; }
	}
	//表中没有对应数据，进行插入
	ht->table[index].key = key;
	ht->table[index].value = value;
	return 0;
}

//删除操作A（据关键字删除）
void DeleByKey(HashTable* ht, int key) {
	int originalindex = HashFunction(key, ht->size);
	int index = originalindex;
	//逆冲突处理
	while (ht->table[index].key != 0) {
		if (ht->table[index].key == key) {
			ht->table[index].key = -1;
			ht->table[index].value = -1;
		}
		index = (index + 1) % ht->size;
		//没有对应的key
		if (index == originalindex) { break; }
	}
}

//删除操作B（据位置删除）
void DeleByLocation(HashTable* ht, int location) {
	ht->table[location-1].key = -1;
	ht->table[location-1].value = -1;
}